package com.zhq.apputil.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.zhq.apputil.R;


/**
 * 将背景图片放在非UI线程绘制，提升APP的效率
 */
public class RootSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
    private float mViewWidth = 0;
    private float mViewHeight = 0;
    private int mResourceId = 0;
    private Context mContext = null;
    private volatile boolean isRunning = false;
    private SurfaceHolder mSurfaceHolder = null;

    public RootSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initRootSurfaceView(context, attrs, defStyleAttr, 0);
    }

    public RootSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initRootSurfaceView(context, attrs, 0, 0);
    }

    private void initRootSurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        mContext = context;
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RootSurfaceView, defStyleAttr, defStyleRes);
        int n = a.getIndexCount();
        mViewWidth = displayMetrics.widthPixels;
        mViewHeight = displayMetrics.heightPixels;
        for (int index = 0; index < n; index++) {
            int attr = a.getIndex(index);
            if (attr == R.styleable.RootSurfaceView_background) {
                mResourceId = a.getResourceId(attr, 0);
            } else if (attr == R.styleable.RootSurfaceView_view_width) {
                mViewWidth = a.getDimension(attr, displayMetrics.widthPixels);
            } else if (attr == R.styleable.RootSurfaceView_view_height) {
                mViewHeight = a.getDimension(attr, displayMetrics.heightPixels);
            }
        }
        a.recycle();
        mSurfaceHolder = getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
        //设置一些参数方便后面绘图
        setFocusable(true);
        setKeepScreenOn(true);
        setFocusableInTouchMode(true);
    }

    private Bitmap getDrawBitmap(float width, float height) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), mResourceId);
        Bitmap resultBitmap = zoomImage(bitmap, width, height);
        return resultBitmap;
    }

    //surface尺寸发生改变的时候调用，如横竖屏切换。
    @Override
    public void surfaceChanged(SurfaceHolder arg0, int format, int width, int height) {
        System.out.println("RootSurfaceView surfaceChanged");
    }

    //surface创建的时候调用，一般在该方法中启动绘图的线程。
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isRunning = true;
        new Thread(this).start();
        System.out.println("RootSurfaceView surfaceCreated");
    }

    //surface被销毁的时候调用，如退出游戏画面，一般在该方法中停止绘图线程。
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isRunning = false;
        System.out.println("RootSurfaceView surfaceDestroyed");
    }

    //页面显示在window
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        System.out.println("RootSurfaceView onAttachedToWindow");
    }

    //view页面被销毁时候
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        System.out.println("RootSurfaceView onDetachedFromWindow");

    }

    @Override
    public void run() {
        while (isRunning) {
            synchronized (mSurfaceHolder) {
                if (!mSurfaceHolder.getSurface().isValid()) {
                    continue;
                }
                drawBackGround(mSurfaceHolder);
            }
            isRunning = false;
            break;
        }
    }

    private void drawBackGround(SurfaceHolder holder) {
        Canvas canvas = holder.lockCanvas();
        if (mViewWidth == 0) {
            mViewWidth = getWidth();
        }
        if (mViewHeight == 0) {
            mViewHeight = getHeight();
        }
        Bitmap bitmap = getDrawBitmap(mViewWidth, mViewHeight);
        canvas.drawBitmap(bitmap, 0, 0, null);
        bitmap.recycle();
        holder.unlockCanvasAndPost(canvas);
    }

    public static Bitmap zoomImage(Bitmap bgimage, float newWidth, float newHeight) {
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = newWidth / width;
        float scaleHeight = newHeight / height;
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
        if (bitmap != bgimage) {
            bgimage.recycle();
            bgimage = null;
        }
        return bitmap;
    }
}